package com.qph.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.qph.base.model.SystemContext;

public class PagerFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;

		SystemContext.setOffset(getOffset(httpRequest));
		SystemContext.setPagesize(getPagesize(httpRequest));
		SystemContext.setSort(getSort(httpRequest));
		SystemContext.setOrder(getOrder(httpRequest));

		try {
			chain.doFilter(request, response);
		} finally {
			// 清空ThreadLocal中的值
			SystemContext.removeOffset();
			SystemContext.removePagesize();
			SystemContext.removeOrder();
			SystemContext.removeTotal();
			SystemContext.removeSort();
		}
	}

	public void init(FilterConfig arg0) throws ServletException {

	}

	private int getOffset(HttpServletRequest request) {
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("page"));
		} catch (NumberFormatException ignore) {
		}
		return offset;
	}

	private int getPagesize(HttpServletRequest request) {
		
		int pageSize = 10;
		
		try {
			pageSize = Integer.parseInt(request.getParameter("rows"));
		}catch (NumberFormatException ignore) {
		}
		
		return pageSize;
	}
	
	private String getSort(HttpServletRequest request) {
		
		return request.getParameter("sort");
	}
	
	private String getOrder(HttpServletRequest request) {
		
		return request.getParameter("order");
	}
}
